<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once dirname(__FILE__) ."/lib/WxPay.Api.php";
require_once dirname(__FILE__) .'/log.php';

set_time_limit(0);
//初始化日志
$logHandler= new CLogFileHandler(dirname(__FILE__) ."/logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

Log::DEBUG("退款开始:" );
$daytimenow_ev56_s = time();

$pin_order = DB::LimitQuery('pin_order', array(
	'condition' => array('state'=>0,"endtime <= $daytimenow_ev56_s "),
	'size' => 5,
	'offset' => 0
));

if($pin_order)
{
	
$access_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.WxPayConfig::APPID.'&secret='.WxPayConfig::APPSECRET;
$accss_token_arr = json_decode(http_get($access_url));
$re_access_token = $accss_token_arr->access_token;

	foreach($pin_order as $pin_info)
	{
		$pin_order_list = DB::LimitQuery('pin_order_list', array(
			'condition' => array('pin_id'=>$pin_info['id']),
		));
		
		if($pin_order_list)
		{
			$tui_flag = true;
			$jjj = 1;
			foreach($pin_order_list as $val)
			{
				$order = Table::Fetch('order', $val['order_id']);
				
				if($order['state'] == 'pay' && $order['rstate'] == 'normal')
				{
					$team = Table::FetchForce('team', $order['team_id']);
					$team = Table::Fetch('team', $order['team_id']);
					team_state($team);
					if ( $team['state'] != 'failure' ) {
						$minus =  $order['quantity'];
						Table::UpdateCache('team', $team['id'], array(
									'now_number' => array( "now_number - {$minus}", ),
						));
						
						Table::UpdateCache('team', $team['id'], array(
									'max_number' => array( "max_number + {$minus}", ),
						));
					}
					
					$user = Table::Fetch('user', $order['user_id'], 'id');
					$openId = $user['open_id'];
					//money
					$transaction_id = $order["trade_no"];
					$total_fee = ($order["origin"]-$order['card'])*100;
					$refund_fee = $total_fee;
					$input = new WxPayRefund();
					$input->SetTransaction_id($transaction_id);
					$input->SetTotal_fee($total_fee);
					$input->SetRefund_fee($refund_fee);
					$refund_no = WxPayConfig::MCHID.date("YmdHis").$jjj;
					$jjj++;
					$input->SetOut_refund_no($refund_no);
					$input->SetOp_user_id(WxPayConfig::MCHID);
					
					$res = (WxPayApi::refund($input));
					
					if($res['result_code'] == 'SUCCESS')
					{
						Table::UpdateCache('order', $val['order_id'], array(
							'express_no' => '',
							));
						Table::UpdateCache('order', $val['order_id'], array(
								'service' => 'cash',
								'rstate' => 'berefund',
								'rereason'=>'开团失败',
								'state' => 'unpay'
						));
						
						$txt ='{
						"touser":"'.$openId.'",
						"msgtype":"text",
						"text":
							{
								 "content":"订单退款: 您的订单'.$val['order_id'].'参团未成功，现退款:'.$order['money'].'元，商品名称：'.$team['title'].'."
							}
						}';
					
						$url ='https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$re_access_token;
						$result = https_post($url,$txt);
						
						Log::DEBUG("退款成功。。。退款日志:退款订单号:" . $val['order_id'].',ten:'.$transaction_id.'   退款金额： '.$order["money"].',退款给：openid='.$openId);
					} else {
						var_dump($order,$res);
						echo '<br><br><br>';
						
						Table::UpdateCache('order', $val['order_id'], array(
								'service' => 'cash',
								'rstate' => 'askrefund',
								'rereason'=>'请手动退款，自动退款失败，失败原因：'.$res['err_code_des']
						));
						//askrefund
						
						
						$tui_flag = false;
						Log::DEBUG("退款失败。原因：{$res[err_code_des]}。。退款日志:退款订单号:" . $val['order_id'].',退款金额： '.$order["money"].',退款给：openid='.$openId);
					}
				}
				//state
			}
		}
		Table::UpdateCache('pin_order', $pin_info['id'], array(
					'state' => 2,
					));
	}
		
}

var_dump('退款成功。',$pin_order);
die();
function https_post($url,$data)
{
	$curl = curl_init();
	curl_setopt($curl,CURLOPT_URL,$url);
	curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
	curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
	curl_setopt($curl,CURLOPT_POST,1);
	curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
	$result = curl_exec($curl);
	if(curl_errno($curl)){
	  return 'Errno'.curl_error($curl);
	}
	curl_close($curl);
	return $result;
}

function http_get($url)
{
	
	$curl = curl_init();
	curl_setopt($curl,CURLOPT_URL,$url);
	curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
	curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
	curl_setopt($curl,CURLOPT_POST,1);
	curl_setopt($curl,CURLOPT_POSTFIELDS,array());
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
	$result = curl_exec($curl);
	curl_close($ch);
	return $result;
}
function printf_info($data)
{
    foreach($data as $key=>$value){
        echo "<font color='#f00;'>$key</font> : $value <br/>";
    }
}

?>
